import fsp from 'fs/promises'
import { htmlToCheerio } from '../lib/cheerio.js'
import path from 'path'
import { dataDir, jsonDir, projectConfig, saveProjectConfig } from '../config.js'
import { glob } from 'glob'
import { NodeHtmlMarkdown } from 'node-html-markdown'

class Plugin {
  constructor() {
    this.page = null
    this.timeout = 5 * 60 * 1000 // 5分钟
  }

  log(...args) {
    console.log('[plugin]', ...args)
  }

  initRoute(koa) {
    this.log('消息列表', 'GET http://127.0.0.1:3001/plugin/chat')
    this.log('接受消息', 'POST http://127.0.0.1:3001/plugin/message')

    koa.router.get('/plugin/task', async ctx => {
      const src = path.join(dataDir, 'singal/**/*.txt').replace(/\\/g, '/')
      const files = await glob(src)
      const config = projectConfig['cs-eval-question']
      if (config.end == 0) config.end = files.length

      const file = files[config.start]
      const message = await fsp.readFile(file, 'utf-8')

      config.start++
      saveProjectConfig()

      ctx.body = {
        code: 0,
        msg: 'success',
        data: {
          message,
        },
      }
    })

    koa.router.get('/plugin/chat', async ctx => {
      const src = path.join(jsonDir, '**/*.json').replace(/\\/g, '/')
      const files = await glob(src)
      const chatIds = files.map(file => {
        return file.split('\\').pop().split('.')[0]
      })

      ctx.body = {
        code: 0,
        msg: 'success',
        data: {
          chatIds,
        },
      }
    })

    koa.router.post('/plugin/message', ctx => {
      const { body } = ctx.request
      const { type, data } = body

      // this.log('message', body)
      this.log('message', type)

      const $ = htmlToCheerio(data.html)

      // 问题
      const question = $('[data-testid="message_text_content"]').first().text()

      // 思考
      const think = $('[data-testid="collapse_quota_block"]')
        .last()
        .find('[data-testid="message_text_content"]')
        .first()
        .text()

      // 正文
      const content = NodeHtmlMarkdown.translate($('[data-testid="message_text_content"]').last().html())

      const saveData = {
        question,
        think,
        content,
      }

      this.log('returnData', saveData)

      // 联网模式
      const isOnline = $('[data-testid="search-reference-ui"]').length ? true : false
      const returnData = {
        isOnline,
      }

      console.log('returnData', returnData)

      if (isOnline) {
        this.log('联网保存')
        fsp.writeFile(path.join(jsonDir, `${data.chatId}.json`), JSON.stringify(saveData))
        fsp.writeFile(path.join(dataDir, `html/${data.chatId}.html`), data.html)
      } else {
        this.log('未联网跳不保存')
      }

      ctx.body = {
        code: 0,
        msg: 'success',
        data: returnData,
      }
    })
  }
}

export default new Plugin()
